package com.sendinfo.alipay;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.bind.JAXBContext;

import org.apache.log4j.Logger;

import com.sendinfo.xspring.util.HttpUtil;
import com.sendinfo.xspring.util.TxtUtil;

public class AlipayUtil {
	private static Logger logger = Logger.getLogger(AlipayUtil.class);

	/**
	 * 得到加密信息
	 * 
	 * @param trans
	 * @param privateKey
	 * @return
	 */
	public static String getContent(Map<String, String> params, String privateKey) {
		List<String> keys = new ArrayList<String>(params.keySet());
		Collections.sort(keys);
		String prestr = "";
		boolean first = true;
		for (int i = 0; i < keys.size(); i++) {
			String key = (String) keys.get(i);
			String value = (String) params.get(key);
			if (value == null || value.trim().length() == 0) {
				continue;
			}
			if (first) {
				prestr = prestr + key + "=" + value;
				first = false;
			} else {
				prestr = prestr + "&" + key + "=" + value;
			}
		}
		return prestr + privateKey;
	}

	/**
	 * 
	 * @param checkUrl
	 * @param partner
	 * @param notifyId
	 * @return
	 */
	public static boolean check(String checkUrl, String partner, String notifyId) {
		String inputLine = "";
		try {
			String urlvalue = checkUrl + "?partner=" + partner + "&notify_id=" + notifyId;
			URL url = new URL(urlvalue);
			HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

			inputLine = in.readLine().toString();
			/*
			 * 输出对应的参数对应错误： 1.invalid命令参数不对 出现这个错误，请检测返回处理中partner和key是否为空
			 * 2.true 返回正确信息 3.false 请检查防火墙或者是服务器阻止端口问题以及验证时间是否超过一分钟
			 */
			if ("true".equals(inputLine))
				return true;
			else
				return false;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

	}

	//执行分润操作。
	public static boolean royaltyExec(AlipayRoyaltyVo royalty) {
		String inputLine = "";
		try {
			String urlStr = royalty.getUrl() + "?service=" + royalty.getService();
			urlStr += "&partner=" + royalty.getPartner();
			urlStr += "&notify_url=" + URLEncoder.encode(royalty.getNotify_url(), royalty.getInput_charset());
			urlStr += "&trade_no=" + royalty.getTrade_no();
			urlStr += "&out_bill_no=" + royalty.getOut_bill_no();
			urlStr += "&royalty_type=" + royalty.getRoyalty_type();
			urlStr += "&royalty_parameters=" + URLEncoder.encode(royalty.getRoyalty_parameters(), royalty.getInput_charset());
			urlStr += "&_input_charset=" + royalty.getInput_charset();
			urlStr += "&sign=" + royalty.getSign();
			urlStr += "&sign_type=" + royalty.getSign_type();
			URL url = new URL(urlStr);
			HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
			String t = in.readLine();
			while (!TxtUtil.isEmpty(t)) {
				inputLine = inputLine + t;
				t = in.readLine();
			}
			JAXBContext context = JAXBContext.newInstance(AlipayResultXml.class);
			InputStream buf = new ByteArrayInputStream(inputLine.getBytes("UTF-8"));
			AlipayResultXml result = (AlipayResultXml) context.createUnmarshaller().unmarshal(buf);
			if (!"T".equals(result.getIs_success()))
				return false;
			else
				return true;
		} catch (Exception ex) {
			ex.printStackTrace();
			return false;
		}
	}

	//支付请验证
	public static String Sign(AlipayTransVo trans, String privateKey) {
		Map<String, String> params = new HashMap<String, String>();
		params.put("service", trans.getService());// 非空
		params.put("partner", trans.getPartner());// 非空
		params.put("return_url", trans.getReturnUrl());
		params.put("notify_url", trans.getNotifyUrl());
		params.put("payment_type", trans.getPayment_type());// 非空
		params.put("seller_email", trans.getSeller_email());
		params.put("out_trade_no", trans.getOut_trade_no());// 非空
		params.put("out_order_no", trans.getOut_order_no());// 非空
		// 支付宝合作伙伴订单号，系统唯一
		params.put("total_fee", trans.getTotal_fee());
		params.put("subject", trans.getSubject());// 非空
		params.put("body", trans.getBody());
		params.put("_input_charset", trans.getInput_charset());// 非空
		params.put("paymethod", trans.getPaymethod());
		params.put("lt_b_pay", trans.getLt_b_pay());
		String str = AlipayUtil.getContent(params, privateKey);
		return TxtUtil.digest(str).toLowerCase();
	}

	//订单查询接口
	public static AlipayQueryResultXml tradeQuery(String outOrderNo) {
		AlipayQueryResultXml result = new AlipayQueryResultXml();
		Map<String, String> params = new HashMap<String, String>();
		params.put("service", AlipayContext.SERVICE_TRADE_QUERY);
		params.put("partner", AlipayContext.PARTNER);
		params.put("out_trade_no", outOrderNo);
		params.put("_input_charset", AlipayContext.INPUT_CHARSET);
		String str = AlipayUtil.getContent(params, AlipayContext.KEY);
		params.put("sign_type", AlipayContext.SIGN_TYPE);
		params.put("sign", TxtUtil.digest(str).toLowerCase());
		String responseText = HttpUtil.doGet(AlipayContext.SERVICE_URL_HTTPS, params, "utf-8");
		JAXBContext context;
		try {
			context = JAXBContext.newInstance(AlipayQueryResultXml.class);
			InputStream buf = new ByteArrayInputStream(responseText.getBytes("UTF-8"));
			result = (AlipayQueryResultXml) context.createUnmarshaller().unmarshal(buf);
			return result;
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			return null;
		}

	}

	/**
	 * @Title: alipayReturnSign
	 * @Description: TODO(支付宝通知签名验证)
	 * @param @param params
	 * @param @param privateKey
	 * @param @return 设定文件
	 * @return String 返回类型
	 * @throws
	 */

	public static AlipayResultXml closeTrade(String outOrderNo) {
		AlipayResultXml result = new AlipayResultXml();
		Map<String, String> params = new HashMap<String, String>();
		params.put("service", AlipayContext.SERVICE_CLOSE_TRADE);
		params.put("partner", AlipayContext.PARTNER);
		params.put("out_order_no", outOrderNo);
		params.put("_input_charset", AlipayContext.INPUT_CHARSET);
		String str = AlipayUtil.getContent(params, AlipayContext.KEY);
		params.put("sign", TxtUtil.digest(str).toLowerCase());
		params.put("sign_type", AlipayContext.SIGN_TYPE);
		String responseText = HttpUtil.doGet(AlipayContext.SERVICE_URL_HTTPS, params, "utf-8");
		JAXBContext context;
		try {
			context = JAXBContext.newInstance(AlipayResultXml.class);
			InputStream buf = new ByteArrayInputStream(responseText.getBytes("UTF-8"));
			result = (AlipayResultXml) context.createUnmarshaller().unmarshal(buf);
			return result;
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			return null;
		}
	}

	@SuppressWarnings("unchecked")
	public static String alipayReturnSign(Map params, String privateKey) {
		List keys = new ArrayList(params.keySet());
		Collections.sort(keys);
		String prestr = "";
		boolean first = true;
		for (int i = 0; i < keys.size(); i++) {
			String key = (String) keys.get(i);
			String value = ((String[]) params.get(key))[0];
			if (key == null || key.equalsIgnoreCase("sign") || key.equalsIgnoreCase("sign_type")) {
				continue;
			}
			if (value == null || value.trim().length() == 0) {
				continue;
			}
			if (first) {
				prestr = prestr + key + "=" + value;
				first = false;
			} else {
				prestr = prestr + "&" + key + "=" + value;
			}
		}
		return TxtUtil.digest(prestr + privateKey).toLowerCase();
	}
}
